package com.walle.gatewayserver.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {

	/**
	 * 解压
	 * @param in
	 * @param charset
	 * @return
	 */
	public static String uncompress(InputStream in,String charset) {
		try {
		   GZIPInputStream gInputStream = new GZIPInputStream(in);
		   byte[] by = new byte[1024];
		   StringBuffer strBuffer = new StringBuffer();
		   int len = 0;
		   while ((len = gInputStream.read(by)) != -1) {
		    strBuffer.append( new String(by, 0, len,charset) );
		   }
		   return strBuffer.toString();
		} catch (IOException e) {
		   e.printStackTrace();
		}
		return null;
	}
	/**
	 * 压缩
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static byte[] compress(byte[] data) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(bos);
		gzip.write(data);
		gzip.finish();
		gzip.close();
		byte[] ret = bos.toByteArray();
		bos.close();
		return ret;
	}
}